﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web.Http;

namespace MetroDataApi.Controllers.Management
{
    public class MonitorPointsDictionaryController : ApiController
    {
        
        // GET api/monitorpointsdictionary
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/monitorpointsdictionary/5
        public string Get(int prjId)
        {
            var list = MonitorPointsDictionaryDescriptionDbHelper.GetFromDb(prjId);
            return JsonConvert.SerializeObject(list);
        }

        // POST api/monitorpointsdictionary
        public void Post([FromBody]string value)
        {
            JObject jsonData = JObject.Parse(value);
            int prjId = jsonData["prjId"].ToObject<int>();
            var dict = jsonData["dict"].ToObject<List<MonitorPointsDictionaryDescription>>();
            MonitorPointsDictionaryDescriptionDbHelper.SetToDb(prjId, dict);
        }

        // PUT api/monitorpointsdictionary/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/monitorpointsdictionary/5
        public void Delete(int id)
        {
        }
    }

    public class MonitorPointsDictionaryDescription
    {
        public string Prefix { get; set; }
        public int Start { get; set; }
        public int End { get; set; }
        public string Location { get; set; }
        public string MonitorType { get; set; }
        public int PrjId { get; set; }

    }

    public  class MonitorPointsDictionaryDescriptionDbHelper
    {
        public static void SetToDb(int prjId, List<MonitorPointsDictionaryDescription> dict)
        {
            //delete all in 
            using (var db = new MetroDataDataContext())
            {
                var list = from mpt in db.MonitorPointsDictionary
                           where mpt.PrjId == prjId
                           select mpt;
                db.MonitorPointsDictionary.DeleteAllOnSubmit(list);

                var newMonitorPointList = new List<MonitorPointsDictionary>();
                foreach (var d in dict)
                {
                    for (int i = d.Start; i <= d.End; i++)
                    {
                        var mp = new MonitorPointsDictionary()
                        {
                            Name = d.Prefix + i.ToString("D2"),
                            PrjId = prjId,
                            Location = d.Location,
                            MonitorType = d.MonitorType
                        };
                        newMonitorPointList.Add(mp);
                    }
                }

                db.MonitorPointsDictionary.InsertAllOnSubmit(newMonitorPointList);
                db.SubmitChanges();
            }

        }

        public static List<MonitorPointsDictionaryDescription> GetFromDb(int prjId)
        {
            var list = new List<MonitorPointsDictionaryDescription>();
            var reg = new Regex(@"\d*[a-zA-z]+");
            using (var db = new MetroDataDataContext())
            {
                var mpoints = from mpt in db.MonitorPointsDictionary
                              where mpt.PrjId == prjId
                              group mpt by mpt.MonitorType into g
                              select g;

                foreach(var mt in mpoints)
                {
                    var mType = mt.Key;
                    var lgroup = from p in mt group p by p.Location into g select g;
                    foreach (var lpt in lgroup)
                    {
                        var location = lpt.Key;

                        var prefixList = from p in lpt
                                         group p by reg.Match(p.Name).Value into g
                                         select g;

                        foreach (var pre in prefixList)
                        {
                            try
                            {
                                var preList = pre.ToList();
                                var numberList = preList.
                                    Select(p => Convert.ToInt32(p.Name.Replace(pre.Key, "")));
                                var description = new MonitorPointsDictionaryDescription()
                                {
                                    Prefix = pre.Key,
                                    Location = location,
                                    MonitorType = mType,
                                    Start = numberList.Min(),
                                    End = numberList.Max(),
                                    PrjId = prjId
                                };
                                list.Add(description);
                            }
                            catch
                            {
                                continue;
                            }
                        }
                                            
                    }
                }
            }
            return list;
        }
    }
}
